﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace UDS.Management.SMS
{
    public enum SmsItemStatus
    {
        DoNotSend = 0,
        Pending = 1,
        Succeeded = 2,
        Failed = 3
    }

    public class SmsItem
    {
        public int Id { get; set; }
        public string Receiver { get; set; }
        public string ReceiverPhone { get; set; }
        public string Sender { get; set; }
        public string Message { get; set; }

        internal static SmsItem[] GetSMSList(SqlConnectionHolder holder)
        {
            List<SmsItem> list = new List<SmsItem>();
            using (var dr = holder.ExecuteReader("dbo.sproc_Mail_GetSMSToSend"))
            {
                while (dr.Read())
                {
                    SmsItem item = new SmsItem();
                    item.Read(dr);

                    list.Add(item);
                }
            }

            return list.ToArray();
        }

        internal void UpdateSMSStatus(SqlConnectionHolder holder, bool succeeded)
        {
            string xml = string.Format(
                "<mails><m id=\"{0}\" status=\"{1}\" /></mails>",
                Id,
                (int)(succeeded ? SmsItemStatus.Succeeded : SmsItemStatus.Failed));

            SqlParameter p = new SqlParameter("@mailStatus", SqlDbType.Xml, -1);
            p.Value = xml;

            holder.Execute("dbo.sproc_Mail_UpdateSMSStatus", new SqlParameter[] { p });
        }

        private void Read(IDataReader dr)
        {
            Id = (int)dr["MailId"];
            Receiver = Convert.ToString(dr["Receiver"]);
            ReceiverPhone = Convert.ToString(dr["ReceiverPhone"]);
            Sender = Convert.ToString(dr["Sender"]);
            Message = Convert.ToString(dr["Body"]);
        }
    }
}
